//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace Microsoft.Research.DataLayer
{
    public class TypeHandlersHelper
    {
        internal static void GetProviders(string alternatePath,
            ref Dictionary<string, PropHandlerBase> propHandlers)
        {
            Assembly me = Assembly.GetExecutingAssembly();
            string myPath = (true == string.IsNullOrEmpty(alternatePath)) ?
                Path.GetDirectoryName(me.Location) : alternatePath;

            foreach (string asmCandidate in Directory.GetFiles(myPath, "Microsoft.Research.DataLayer.OPCHandlers.*.dll"))
            {
                Assembly loadedCandidate = Assembly.LoadFile(asmCandidate);
                System.Type provInfo = loadedCandidate.GetType("Microsoft.Research.DataLayer.HandlerInfoProvider");
                PropertyInfo provInfoInstance = provInfo.GetProperty("Providers", BindingFlags.Public | BindingFlags.Static);
                PropHandlerBase[] provListInCandidate = (PropHandlerBase[])provInfoInstance.GetValue(null, null);
                foreach(PropHandlerBase handler in provListInCandidate)
                {
                    propHandlers.Add(handler.ObjectName, handler);
                }
            }
        }

        internal static void GetBlobHandlers(string alternatePath, ref Dictionary<string, BlobHandlerBase> blobHandlers)
        {
            Assembly me = Assembly.GetExecutingAssembly();
            string myPath = (true == string.IsNullOrEmpty(alternatePath)) ?
                Path.GetDirectoryName(me.Location) : alternatePath;

            foreach (string asmCandidate in Directory.GetFiles(myPath, "Microsoft.Research.DataLayer.OPCBlobHandlers.*.dll"))
            {
                Assembly loadedCandidate = Assembly.LoadFile(asmCandidate);
                System.Type provInfo = loadedCandidate.GetType("Microsoft.Research.DataLayer.BlobHandlerInfoProvider");
                PropertyInfo provInfoInstance = provInfo.GetProperty("Providers", BindingFlags.Public | BindingFlags.Static);
                BlobHandlerBase[] provListInCandidate = (BlobHandlerBase[])provInfoInstance.GetValue(null, null);
                foreach (BlobHandlerBase handler in provListInCandidate)
                {
                    blobHandlers.Add(handler.ObjectName, handler);
                }
            }
        }
    }
}
